package com.study.springcloudgateway.routeFilterFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.api.Result;
import com.study.clients.IUserAuthFeignClients;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @description：登录拦截
 * @author：李军荣
 * @date: 2020/12/28 16:14
 */
@Slf4j
@PropertySource(value = "classpath:loginFilter.properties")
@Order(0)
@Component
public class AuthLoginFilter implements GlobalFilter{

    @Value("#{'${jwt.ignoreUrls}'.split(',')}")
    List<String> ignoreUrls;

    @Autowired
    private IUserAuthFeignClients userAuthFeignClients;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        if(ignoreUrls != null && ignoreUrls.contains(serverHttpRequest.getPath())){
            chain.filter(exchange);
        }
        String token = serverHttpRequest.getHeaders().getFirst("access_token");
        if(StringUtils.isEmpty(token)){
            return error(exchange,"尚未登录");
        }
        Result<String> result =userAuthFeignClients.validToken(token);
        if(result.getCode() == 200){
            ServerHttpRequest request = serverHttpRequest.mutate().header("uid",result.getData()).build();
            return  chain.filter(exchange.mutate().request(request).build());
        }
        return error(exchange,result.getMsg());
    }

    public Mono<Void> error(ServerWebExchange exchange, String msg){
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        Result result = new Result.Builder().customize(HttpStatus.UNAUTHORIZED.value(),msg).bulider();
        ObjectMapper objectMapper = new ObjectMapper();
        String re = "";
        try {
            re = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
             log.info("GATEWAY AuthLoginFilter Exception"+e);
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(re.getBytes());
        return  response.writeWith(Flux.just(dataBuffer));
    }
}
